<?php

namespace mpend\modules\h5\controllers;

use Yii;
use mpend\components\Controller;
use mpend\modules\h5\models\RecentArticleSearch;
use common\logics\TslineArticleLogic;
use common\models\user\UserLike;
use common\models\tsline\TslineArticleStatistic;

/**
 * 点赞相关
 * Default controller for the `h5` module
 */
class LikeController extends Controller {

    public $modelClass = 'mpend\modules\h5\models\ArticleSearch';

    /**
     * @inheritdoc
     */
    public function actionArticle($id) {

        $model = UserLike::findOrNew([
            'model' => UserLike::MODEL_ARTICLE,
            'model_id' => $id,
            'user_id' => $this->token->user_id,
        ]);

        $step = 0;
        $liked = false;
        if (!$model->isNewRecord) {
            if (!$model->delete()) {
                parent::error('取消点赞失败');
            }
            $step = -1;
            $liked = false;
        } else {
            if (!$model->save()) {
                parent::error('点赞失败', $model->firstErrors);
            }
            $step = 1;
            $liked = true;
        }

        TslineArticleStatistic::updateAllCounters(['likes' => $step], ['article_id' => $id]);

        return $liked;
    }

    /**
     * @inheritdoc
     */
    public function actionRecent($time) {
        /* @var $modelClass \mpend\modules\h5\models\ArticleSearch */
        $model = new RecentArticleSearch($time);
        return $model->search();
    }

    /**
     * @inheritdoc
     */
    public function actionView($id) {
        return TslineArticleLogic::findOne($id);
    }

    /**
     * @inheritdoc
     */
    public function actionLike($id) {
        return TslineArticleLogic::findOne($id);
    }

}
